#!/usr/bin/env bash

# This file is part of libmarco
# http://code.google.com/p/libmarco/

# The watchdog function terminates this script unless it terminates earlier on his own
# Useful for script that may block indefinitely
# Warning: if the script is invoked by another script (rather than directly from the shell)
# it may not work properly

max_running_time=10;

# Example function that terminates within the time limit
function fast_function () {
	echo "Fast function, args: $*"
	sleep 3
	echo "Fast function, terminating"	
}

# Example function that gets killed by the watchdog after the time expires
function slow_function () {
	echo "Slow function, args: $*"
	sleep 60
	echo "Slow function, terminating"	
}

function watchdog_timer () {
	script_pid=$1;
	# echo "Watching process ${script_pid}"
	sleep $max_running_time;
	echo " >>> Watchdog timer expired, terminating <<<"
	kill $script_pid
	exit 1;
}


function watchdog () {
	command="$1";
	shift;
	args="$*"
	
	# Start watchdog
	this_process_pid=$$;
	# echo this_process_pid=${this_process_pid};

	watchdog_timer ${this_process_pid} &
	local wd_pid=$!;
	
	# Launch command
	$command $args
	
	# If we are here, the command terminated
	# before the watchdog timer expired
	kill $wd_pid;
}

# Example commands with watchdog

watchdog ls -la $HOME > /dev/null
echo

watchdog fast_function arg1 arg2 arg3
echo

# this is going to be killed
watchdog slow_function  arg1 arg2 
echo



